package cn.healthlink.no_5.bfpp;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionVisitor;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.util.StringValueResolver;
import java.util.HashSet;
import java.util.Set;

/**
 * @author dengzhiyuan
 * @version 1.0
 * @time 2021/2/20 18:25
 */
public class ReplaceFieldValuePostProcessor implements BeanFactoryPostProcessor {

	private Set<String> obscenities;

	public ReplaceFieldValuePostProcessor() {
		this.obscenities = new HashSet<>();
	}

	public Set<String> getObscenities() {
		return obscenities;
	}

	public void setObscenities(Set<String> obscenities) {
		this.obscenities.clear();
		for (String obscenity: obscenities) {
			this.obscenities.add(obscenity);
		}
	}

	public boolean isObscene(Object value){
		String upperWord = value.toString().toUpperCase();
		return this.obscenities.contains(upperWord);
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		String[] beanNames = beanFactory.getBeanDefinitionNames();
		for (String name : beanNames) {
			BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
			StringValueResolver valueResolver = new StringValueResolver() {
				@Override
				public String resolveStringValue(String strVal) {
					if (isObscene(strVal)) {
						return "******";
					}
					return strVal;
				}
			};
			BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);
			visitor.visitBeanDefinition(beanDefinition);
		}
	}
}
